<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item class="mr" label="报警ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入"
          clearable
          style="width: 260px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="mr" label="设备ID" prop="equipId">
        <el-input
          v-model="queryParams.equipId"
          placeholder="请输入"
          clearable
          style="width: 260px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="mr" label="报警级别" prop="alarmLevel">
        <el-select
          v-model="queryParams.alarmLevel"
          clearable
          placeholder="请选择"
          style="width: 260px"
        >
          <el-option
            v-for="{ label, value } in sys_alarm_level"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="mr" label="报警值" prop="alarmValue">
        <el-input
          v-model="queryParams.alarmValue"
          placeholder="请输入"
          clearable
          style="width: 260px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="mr" label="报警内容" prop="alarmContent">
        <el-input
          v-model="queryParams.alarmContent"
          placeholder="请输入"
          clearable
          style="width: 260px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="mr" label="确认人" prop="confirmBy">
        <el-input
          v-model="queryParams.confirmBy"
          placeholder="请输入"
          clearable
          style="width: 260px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" style="width: 360px">
        <el-date-picker
          clearable
          v-model="dateRange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item style="float: right; margin-right: 60px">
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          v-hasPermi="['alarm:records:query']"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['alarm:records:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['alarm:records:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['alarm:records:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['alarm:records:export']"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordsList"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column label="报警ID" width="80" align="center" prop="id">
        <template #default="{ row }"> No.{{ row.id }} </template>
      </el-table-column>
      <el-table-column label="设备ID" align="center" prop="equipId" />
      <el-table-column label="报警级别" align="center" prop="alarmLevel">
        <template #default="{ row }">
          <dict-tag :options="sys_alarm_level" :value="row.alarmLevel" />
        </template>
      </el-table-column>
      <el-table-column label="报警类型" align="center" prop="alarmType">
        <template #default="{ row }">
          <dict-tag :options="sys_alarm_type" :value="row.alarmType" />
        </template>
      </el-table-column>
      <el-table-column label="报警值" align="center" prop="alarmValue" />
      <el-table-column label="正常范围" align="center" prop="normalRange" />
      <el-table-column label="报警内容" align="center" prop="alarmContent" />
      <el-table-column
        label="开始时间"
        width="100"
        align="center"
        prop="beginTime"
      />
      <el-table-column
        label="结束时间"
        width="100"
        align="center"
        prop="endTime"
      />
      <el-table-column label="确认人" align="center" prop="confirmBy" />
      <el-table-column label="确认时间" align="center" prop="confirmTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding  fixed-width"
      >
        <template #default="{ row }">
          <el-button
            type="text"
            icon="View"
            @click="handleView(row)"
            v-hasPermi="['alarm:records:detail']"
            >详细</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报警信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        :model="form"
        :rules="rules"
        ref="alarmRecordsRef"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备ID" prop="equipId">
              <el-input v-model="form.equipId" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警级别" prop="alarmLevel">
              <el-select
                v-model="form.alarmLevel"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="{ label, value } in sys_alarm_level"
                  :key="value"
                  :label="label"
                  :value="value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警类型" prop="alarmType">
              <el-select
                v-model="form.alarmType"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="{ label, value } in sys_alarm_type"
                  :key="value"
                  :label="label"
                  :value="value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警值" prop="alarmValue">
              <el-input-number
                style="width: 250px"
                v-model="form.alarmValue"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="正常范围" prop="normalRange">
              <el-col :span="16">
                <div class="slider-demo-block">
                  <el-slider v-model="normalRange" range :max="100" />
                </div>
              </el-col>
              <el-col :span="7" style="text-align: center">{{
                normalRange
              }}</el-col>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="时间">
              <el-date-picker
                v-model="dateRange2"
                type="datetimerange"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 460px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报警内容" prop="alarmContent">
              <el-input v-model="form.alarmContent" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认人" prop="confirmBy">
              <el-input placeholder="请输入" v-model="form.confirmBy" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认时间">
              <el-date-picker
                v-model="form.confirmTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报警记录详细 -->
    <el-dialog
      title="报警记录详细"
      v-model="openView"
      width="600px"
      append-to-body
    >
      <el-form :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="报警ID：">{{ 'No.' + form.id }}</el-form-item>
            <el-form-item label="报警级别：">
              <dict-tag :options="sys_alarm_level" :value="form.alarmLevel" />
            </el-form-item>
            <el-form-item label="报警类型：">
              <dict-tag :options="sys_alarm_type" :value="form.alarmType" />
            </el-form-item>
            <el-form-item label="开始时间：">
              {{ form.beginTime }}
            </el-form-item>
            <el-form-item label="结束时间：">
              {{ form.endTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备ID：">{{ form.equipId }}</el-form-item>
            <el-form-item label="报警值：">{{ form.alarmValue }}</el-form-item>
            <el-form-item label="正常范围：">{{
              form.normalRange
            }}</el-form-item>
            <el-form-item label="确认人：">
              {{ form.confirmBy }}
            </el-form-item>
            <el-form-item label="确认时间：">
              {{ form.confirmTime }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报警内容：">{{
              form.alarmContent
            }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="alarmRecords">
import {
  listRecords,
  getRecords,
  delRecords,
  addRecords,
  updateRecords
} from '@/api/alarm/records'

const { proxy } = getCurrentInstance()

/* 获取单位字典 */
const { sys_alarm_level } = proxy.useDict('sys_alarm_level') //报警级别
const { sys_alarm_type } = proxy.useDict('sys_alarm_type') //报警类型

const recordsList = ref([])
const open = ref(false)
const loading = ref(true)
const sns = ref([])
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const openView = ref(false)
const title = ref('')
const total = ref(0)
const dateRange = ref([])
const dateRange2 = ref([])
const normalRange = ref([0, 100])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    equipId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询报警记录列表 */
function getList() {
  loading.value = true
  const [beginTime, endTime] = dateRange.value ?? []
  listRecords({ ...queryParams.value, beginTime, endTime }).then((response) => {
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

/* 重置新增和修改表单 */
function reset() {
  normalRange.value = [0, 100]
  dateRange2.value = []
  form.value = {}
  proxy.resetForm('alarmRecordsRef')
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加报警信息'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const recordsId = row.id || ids.value
  getRecords(recordsId).then((response) => {
    form.value = response.data
    dateRange2.value = [response.data.beginTime, response.data.endTime]
    normalRange.value = [
      parseInt(response.data.normalRange.split('~')[0]),
      parseInt(response.data.normalRange.split('~')[1])
    ]
    open.value = true
    title.value = '修改报警信息'
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const recordsIds = row.id || ids.value
  proxy.$modal
    .confirm('是否确认序号为："' + sns.value + '"的数据项?')
    .then(function () {
      return delRecords(recordsIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'ec/alarm/export',
    {
      ...queryParams.value
    },
    `alarm_${new Date().getTime()}.xlsx`
  )
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['alarmRecordsRef'].validate((valid) => {
    if (valid) {
      let params = Object.assign({}, form.value, {
        normalRangeMin: normalRange.value[0],
        normalRangeMax: normalRange.value[1],
        beginTime: dateRange2.value[0],
        endTime: dateRange2.value[1]
      })
      if (form.value.id != undefined) {
        updateRecords(params).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addRecords(params).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 把每一行的索引放进row */
function tableRowClassName({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  sns.value = selection
    .map((item) => +item.index)
    .sort(function (a, b) {
      return a - b
    })
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 详细按钮操作 */
function handleView(row) {
  openView.value = true
  form.value = row
}

// 初始化列表
getList()
</script>
<style lang="scss" scoped>
.mr {
  margin-right: 30px;
}
.slider-demo-block {
  margin-left: 10px;
}
</style>
